<?php

namespace app\admin\service;

use app\admin\validate\ArticleValidate;
use support\spark\exception\ApiException;
use support\spark\model\system\Article;
use think\Validate;

class ArticleService
{
    /**
     * 获取文章列表
     * @param $param
     * @return array
     * @throws \think\db\exception\DbException
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $name = $param['title'] ?? '';
        $where = [];
        if (!empty($name)) {
            $where[] = ['title', 'like', '%' . $name . '%'];
        }

        $articleModel = new Article();
        $list = $articleModel->getPaginateList($where, ['*'], ['id' => 'desc'], ['cateInfo'], $limit);
        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加文章
     * @param $param
     * @return array|\think\response\Json
     */
    public function addArticle($param)
    {
        // 检验完整性
        $validate = new ArticleValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $articleModel = new Article();
        $has = $articleModel->checkUnique([
            'title' => $param['title']
        ]);

        if (!empty($has)) {
            throw  new  ApiException('文章标题已经存在', -1);
        }

        $param['create_time'] = now();
        $param['update_time'] = now();
        $articleModel->insertOne($param);
        return dataReturn(0, '添加成功');
    }

    /**
     * 编辑文章
     * @param $param
     * @return array|\think\response\Json
     */
    public function editArticle($param)
    {
        // 检验完整性
        $validate = new ArticleValidate();
        if (!$validate->check($param)) {
            throw  new  ApiException($validate->getError(), -1);
        }
        $articleModel = new Article();

        $where[] = ['id', '<>', $param['id']];
        $where[] = ['title', '=', $param['title']];
        $has = $articleModel->checkUnique($where);

        if (!empty($has)) {
            throw  new  ApiException('文章标题已经存在', -1);
        }

         $articleModel->updateById($param, $param['id']);
        return dataReturn(0, '编辑成功');
    }
}